//买卖股票的最佳时机 IV
//测试链接：https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iv/description/
public class MaxProfit4 {
    public int maxProfit(int k, int[] prices) {
        // 预处理
        int n = prices.length, INF = 0x3f3f3f3f;
        k = Math.min(k, n / 2);
        int[][] f = new int[n][k + 1];
        int[][] g = new int[n][k + 1];
        // 初始化
        for (int j = 0; j <= k; j++)
            f[0][j] = g[0][j] = -INF;
        f[0][0] = -prices[0];
        g[0][0] = 0;
        // 填表
        for (int i = 1; i < n; i++)
            for (int j = 0; j <= k; j++) {
                f[i][j] = Math.max(f[i - 1][j], g[i - 1][j] - prices[i]);
                g[i][j] = g[i - 1][j];
                if (j >= 1)
                    g[i][j] = Math.max(g[i][j], f[i - 1][j - 1] + prices[i]);
            }
        int ret = 0;
        for (int j = 0; j <= k; j++)
            ret = Math.max(ret, g[n - 1][j]);
        return ret;
    }
}
